using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;

namespace Callista.TFSBuildAlert
{
    [DataContract(Namespace = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03")]
    public class SubscriptionInfo
    {
        [DataMember()]
        public string ID;
        [DataMember()]
        public string Subscriber;
        [DataMember()]
        public string Classification;
    }

    [ServiceContract(Namespace = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03")]
    interface INotificationService
    {
        [OperationContract(Action = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03/Notify")]
        void Notify(string eventXml, string tfsIdentityXml, SubscriptionInfo SubscriptionInfo);
    }

    public class NotificationService : INotificationService
    {
        public void Notify(string eventXml, string tfsIdentityXml, SubscriptionInfo subscriptionInfo)
        {
            BuildCompletionEvent buildCompletionEvent = Deserialize<BuildCompletionEvent>(eventXml);
            if (buildCompletionEvent.CompletionStatus.ToUpper() == "FAILED" )
            {
                Program.Current.Alert();
            }
        }

        private static T Deserialize<T>(string message)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(message);
            XmlTextReader xr = new XmlTextReader(sr);
            return (T)xs.Deserialize(xr);
        }

    }
}
